//
//  ADJgSDKInterstitialAdapter.m
//  AnyThinkSDKDemo
//
//  Created by 刘娟 on 2024/9/25.
//  Copyright © 2024 抽筋的灯. All rights reserved.
//

#import "ADJgSDKInterstitialAdapter.h"
#import <AnyThinkInterstitial/AnyThinkInterstitial.h>
#import "ADJgSDKInterstitialCustomEvent.h"
#import "ADJgSDKInterstitialAdContainer.h"
#import "ATADJgSDKBiddingRequest.h"
#import "ATADJgSDKBiddingManager.h"

@interface ADJgSDKInterstitialAdapter ()

@property(nonatomic, readonly) ADJgSDKInterstitialCustomEvent *customEvent;

@property (nonatomic, strong) ADJgSDKInterstitialAdContainer *intertitialAdContainer;

@end

@implementation ADJgSDKInterstitialAdapter

+(BOOL) adReadyWithCustomObject:(id)customObject info:(NSDictionary*)info {
    return customObject;
}

+(void) showInterstitial:(ATInterstitial*)interstitial inViewController:(UIViewController*)viewController delegate:(id<ATInterstitialDelegate>)delegate {
    //Here for full screen video ad, we also use id<ATWMInterstitialAd>, for the presenting methods are the same.
    ADJgSDKInterstitialAdContainer *intertitialAd = interstitial.customObject;
    [intertitialAd showInterstitialAdWithRootViewController:viewController];
    interstitial.customEvent.delegate = delegate;
}

-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo {
    self = [super init];
    if (self != nil) {
        if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
            [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
            [ADJgSDK initWithAppId:serverInfo[@"app_id"] completionBlock:^(NSError * _Nullable error) {
                if(error){
                    [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                    NSLog(@"ADJgSDK - 初始化失败：%@",error);
                }else{
                    NSLog(@"ADJgSDK - 初始化成功");
                }
            }];
                    
        }

       
    }
    return self;
}

-(void) loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion {
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_customEvent = [[ADJgSDKInterstitialCustomEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
        self->_customEvent.requestCompletionBlock = completion;
        
        NSString *bidId = serverInfo[kATAdapterCustomInfoBuyeruIdKey];
        if (bidId.length) {
            
            ATADJgSDKBiddingRequest *request = [[ATADJgSDKBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"slot_id"]];
            
            if (request.customObject!=nil) { // load secced
                self.intertitialAdContainer = request.customObject;
                self.intertitialAdContainer.delegate = self->_customEvent;
                self->_customEvent.interstitialAdContainer = self.intertitialAdContainer;
                [self->_customEvent trackInterstitialAdLoaded:self.intertitialAdContainer adExtra:nil];
            } else { // fail
//                NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:ATADLoadingErrorCodeThirdPartySDKNotImportedProperly userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load intertitial.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
                [self->_customEvent trackInterstitialAdLoadFailed:nil];
            }
            [[ATADJgSDKBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"slot_id"]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_customEvent loadInterstitialAdWithPosId:serverInfo[@"slot_id"]];
            });
        }
    });
}

#pragma mark - Header bidding
#pragma mark - c2s
+(void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {
    NSLog(@"%s", __FUNCTION__);
    if (NSClassFromString(@"ADJgSDK") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"ADJgSDK is not imported"}]); }
        return;
    }
    
    if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
        [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
        [ADJgSDK initWithAppId:info[@"app_id"] completionBlock:^(NSError * _Nullable error) {
            if (error){
                [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                NSLog(@"ADJgSDK - 初始化失败%@",error);
            } else {
                NSLog(@"ADJgSDK - 初始化成功");
                ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
                ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
                request.unitGroup = unitGroupModel;
                request.placementID = placementModel.placementID;
                request.bidCompletion = completion;
                request.unitID = info[@"slot_id"];
                request.extraInfo = info;
                request.adType = ESCAdFormatInterstitial;
                ADJgSDKInterstitialAdContainer *interstitialAdContainer = [[ADJgSDKInterstitialAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil];
                request.customObject = interstitialAdContainer;
                [biddingManage startWithRequestItem:request];
                [interstitialAdContainer loadInterstitialAd];
                
            }
        }];
                
    }else{
        ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
        ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
        request.unitGroup = unitGroupModel;
        request.placementID = placementModel.placementID;
        request.bidCompletion = completion;
        request.unitID = info[@"slot_id"];
        request.extraInfo = info;
        request.adType = ESCAdFormatInterstitial;
        ADJgSDKInterstitialAdContainer *interstitialAdContainer = [[ADJgSDKInterstitialAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil];
        request.customObject = interstitialAdContainer;
        [biddingManage startWithRequestItem:request];
        [interstitialAdContainer loadInterstitialAd];
    }
}


+ (void) sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    ADJgSDKInterstitialAdContainer *interstitialAdContainer = (ADJgSDKInterstitialAdContainer *)customObject;
#if DEBUG
    NSLog(@"ADJgSDK - 插屏 - 上报竞赢价格：%ld",[interstitialAdContainer getBidPrice]);
#endif
}

+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    //美元转人民币，转换为分
    CGFloat cnyPrice = price.floatValue * 6.3 * 100;
    ADJgSDKInterstitialAdContainer *interstitialAdContainer = (ADJgSDKInterstitialAdContainer *)customObject;
#if DEBUG
    NSLog(@"ADJgSDK - 插屏 - 上报竞败；竞赢价格：%ld",@(cnyPrice).integerValue);
#endif
}

@end
